<template>
  <div class="container" :class="page==1?'zhanlue':''">
    <div class="card-container">
      <div class="search">
        <a-form-model layout="inline">
          <a-row type="flex" >
            <a-col :xxl="6" :xl="12" :lg="24" :md="24" :sm="24" :xs="24" >
              <a-form-item label="选择周期" :labelAlign="labelAlign" :labelCol="{xxl:{span: 5},xl:{span: 3},lg:{span:4},md:{span:4},sm:{span:4},xs:{span: 12}}" :wrapperCol="{xxl:{span: 18},xl:{span: 18},lg:{span:24},md:{span: 24},sm:{span: 24},xs:{span: 24}}" style="width: 100%;">
                <a-select v-model="numValue" @change="getData">
                  <a-select-option :value="item.value" v-for="item in pfOptions" :key="item.value">{{item.label}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>

      <div class="totalContainer" v-if="false">
        <a-row type="flex" justify="space-between" >
          <a-col :xxl="item.xxl" :xl="item.xl" :md="item.md" :sm="item.sm" :xs="item.xs" class="total-col" v-for="(item,index) in accountData" :key="index">
            <a-row type="flex" justify="space-between" style="height:100%;">
              <a-col :span="11" class="total-item" style="margin-top:0;" v-for="(item2, index2) in item.children" :key="index2">
                <div class="title">{{item2.title}}</div>
                <div class="p" style="height: 100%;">
                  <div v-if="item2.isPercent">
                    <countTo :startVal='0' :endVal='parseFloat((totalList[item2.key] || 0)*100)' :duration='800' :decimals="item2.decimals"></countTo> %
                  </div>
                  <countTo v-else :startVal='0' :endVal='parseFloat((totalList[item2.key] || 0))' :duration='800' :decimals="item2.decimals"></countTo>
                </div>
              </a-col> 
            </a-row>
          </a-col>
        </a-row>
      </div>

      <CustomTable 
        class="customTable"
        rowKey="username"
        title="账户数据" 
        :dataSource="dataSource" 
        :columns="columns" 
        :loading="loading"
        :downloadTitle="downloadTitle"
        :pagination="{showTotal:total => `更新于：${lastUpdateTime}，共 ${total} 条数据`, pageSize: pageSize,showLessItems: true, showSizeChanger:true,pageSizeOptions:['10', '20', '50', '100']}"
        @change="onChange"
        :scroll="{x:1200}"
      >
        <div slot="username" slot-scope="{record}" >
          <a-tooltip>
            <template slot="title">
              {{record.username}}
            </template>
            <a :href="'https://shoppingads.baidu.com/shop/manageCenter/dashboard/campaignList/target/0/user/'+record.ucid" target="_blank" style="display: block;cursor: pointer;;white-space: nowrap;">{{record.username}}</a>
          </a-tooltip>
        </div>
        <div slot="ucid" slot-scope="{record}">
          {{ record.ucid || '' }}
        </div>
        <div slot="ctr" slot-scope="{record}">
          {{(record.ctr*100).toFixed(2) + '%'}}
        </div>
        <div slot="profit" slot-scope="{record}" :style="record.profit <= 0?'color:#0ebe98':'color:#f73131'">
          {{record.profit ? parseFloat(record.profit).toFixed(2) : '-'}}
        </div>
        <div slot="productCost" slot-scope="{record}">
          {{record.productCost || 0}}
        </div>
        <div slot="cvr80" slot-scope="{record}">
          {{(record.cvr80*100).toFixed(2) + '%'}}
        </div>
        <div slot="cvr90" slot-scope="{record}">
          {{(record.cvr90*100).toFixed(2) + '%'}}
        </div>
        <div slot="dsOcpcConversionsDetail82CVR" slot-scope="{record}">
          {{(record.dsOcpcConversionsDetail82CVR*100).toFixed(2) + '%'}}
        </div>
        <div slot="dsOcpcConversionsDetail83CVR" slot-scope="{record}">
          {{(record.dsOcpcConversionsDetail83CVR*100).toFixed(2) + '%'}}
        </div>
        <div slot="dsOcpcConversionsDetail84CVR" slot-scope="{record}">
          {{(record.dsOcpcConversionsDetail84CVR*100).toFixed(2) + '%'}}
        </div>
        <div slot="dsOcpcConversionsDetail87CVR" slot-scope="{record}">
          {{(record.dsOcpcConversionsDetail87CVR*100).toFixed(2) + '%'}}
        </div>
        <div slot="dsOcpcConversionsDetail82UvCVR" slot-scope="{record}">
          {{(record.dsOcpcConversionsDetail82UvCVR*100).toFixed(2) + '%'}}
        </div>
        <div slot="dsOcpcConversionsDetail82UvCost" slot-scope="{record}">
          {{(record.dsOcpcConversionsDetail82UvCost).toFixed(2)}}
        </div>
        <div slot="roi" slot-scope="{record}">
          {{record.roi}}
        </div>
        <div slot="cvr" slot-scope="{record}">
          <span v-if="record.cvr">{{(record.cvr*100).toFixed(2) + '%'}}</span>
          <span v-else>-</span>
        </div>
        <div slot="cost" slot-scope="{record}">
          {{parseFloat(record.cost).toFixed(2)}}
        </div>
        <div slot="dsOcpcConversionsDetail80Amount" slot-scope="{record}">
          {{parseFloat(record.dsOcpcConversionsDetail80Amount).toFixed(2)}}
        </div>
        <div slot="cost80" slot-scope="{record}">
          {{parseFloat(record.cost80).toFixed(2)}}
        </div>
        <div slot="kdj" slot-scope="{record}">
          {{(record.kdj).toFixed(2)}}
        </div>
        <div slot="gmv" slot-scope="{record}">
          {{parseFloat(record.gmv).toFixed(2)}}
        </div>
        <div slot="cdcb" slot-scope="{record}">
          {{(record.cdcb).toFixed(2)}}
        </div>
        <div slot="pf" slot-scope="{record}">
          {{parseFloat(record.pf).toFixed(2)}}
        </div>
        <div slot="lirun" slot-scope="{record}">
          {{parseFloat(record.lirun).toFixed(2)}}
        </div>
        <div slot="cost90" slot-scope="{record}">
          {{(record.cost90).toFixed(2)}}
        </div>
        <div slot="productGmv" slot-scope="{record}">
          {{parseFloat(record.productGmv).toFixed(2)}}
        </div>
        <div slot="closedAmount" slot-scope="{record}">
          {{parseFloat(record.closedAmount).toFixed(2)}}
        </div>
        <div slot="dsOcpcConversionsDetail90" slot-scope="{record}">
          {{parseFloat(record.dsOcpcConversionsDetail90).toFixed(2)}}
        </div>
        <div slot="dsOcpcConversionsDetail80Cost" slot-scope="{record}">
          {{record.dsOcpcConversionsDetail80Cost == 0 ? '-' : parseFloat(record.dsOcpcConversionsDetail80Cost).toFixed(2)}}
        </div>
        <div slot="dsOcpcConversionsDetail90Cost" slot-scope="{record}">
          {{record.dsOcpcConversionsDetail90Cost == 0 ? '-' : parseFloat(record.dsOcpcConversionsDetail90Cost).toFixed(2)}}
        </div>
      </CustomTable>
    </div>
  </div>
</template>

<script>
import CustomTable from '@/components/table/CustomTable'
import moment from 'moment'
import countTo from 'vue-count-to';
import columns from './columns'
import accountData from './accountData'
import {getBdAccountList, getOptimizerList} from '@/api/xinxiliu/account'
import {compensationReport, getAccountSummary,getLastUpdateTime,compensationReportSelect} from '@/api/dianshang/dianshang'
import {getProductList} from '@/api/dianshang/dianshang'
import { deepCopyArray, deepCopyObject } from '@/utils/util';

export default {
  data() {
    return {
      moment,
      accountData,
      chartTimeSelect: 1, // 选择时间
      accountType: 0, // 选择类型
      superid: 0, // 选择账户
      youhuashiId:0, // 选择优化师
      userData: [], // 账户列表
      youhuashi: [], // 优化师列表
      loading: false,
      form:{ // 时间选择
        start_date: moment().add('days').format("YYYY-MM-DD"),
        end_date: moment().add('days').format("YYYY-MM-DD"),
      },
      product_name: 0, // 产品筛选字段
      lastUpdateTime: '', //最后更新时间
      pageSize: 10,
      dataSource: [],  // table的数据
      dataSourceCopy: [],
      totalData:{},
      productList:[], // 产品列表
      downloadTitle:'账户报表', //下载文件名称
      columns,
      labelAlign: 'right',
      page: 1,
      pfOptions: [],
      numValue: '',
      totalList:{
        atv80:0, // 直播客单价
        atv90:0, // 商品客单价
        cost80:0, // 直播总消费
        cost90:0, // 商品总消费
        dsOcpcConversionsDetail80:0, // 直播间成单量
        dsOcpcConversionsDetail90:0, // 商品成单量
        dsOcpcConversionsDetail80Amount:0, //直播间成单总金额
        productGmv:0, //商品支付成功总金额
        dsOcpcConversionsDetail80Cost: 0, //播间成单成本
        dsOcpcConversionsDetail90Cost: 0, //商品成单成本
        impression: 0,
        click: 0,
        cost: 0,
        cpc: 0,
        ctr:0,
        cvr:0,
      },
    }
  },
  created() {
    this.init()
  },
  mounted() {
  },
  activated() {
    this.watchWindowWidth()
    this.$EventBus.$on('onresize', this.watchWindowWidth)
  },
  methods: {
    init() {
      this.getPFSelect()
      // this.getData()
      // this.getUserData()
      // this.getOptimizerList()
      this.getLastUpdateTime()
      // this.getProductList()
    },
    getData() {
      this.getRiData()
      // this.getTotalData()
    },
    getRiData() {
      // 获取账户列表数据
      this.loading = true;
      let params = {
        num:this.numValue,
      }
      compensationReport(params).then((res) => {
        this.loading = false;
        this.downloadTitle = this.xlsxName('账户报表')
        if (res.errcode == 0) {
          this.dataSourceCopy = deepCopyArray(res.data.list)
          this.totalData = deepCopyObject(res.data.total)
          this.dataSource = res.data.list
          this.dataSource.unshift(Object.assign({
            username:'汇总',
            product_name:'汇总',
          }, res.data.total))
        }
      }).catch(()=>{
        this.loading = false;
      });
    },
    getPFSelect() {
      this.loading = true;
      compensationReportSelect({}).then((res) => {
        if (res.errcode == 0) {
          this.pfOptions = res.data
          this.numValue = 1
          this.getData()
        }
      }).catch(() => {
        
      });
    },
    getTotalData() {
      // 获取合计数据
      let params = {
        type:this.chartTimeSelect,
      }
      if (this.accountType != 0) {
        params.accountType = this.accountType
      }
      if(this.chartTimeSelect == 7){
        Object.assign(params, this.form)
      }
      if (this.superid != 0) {
        params.superid = this.superid
      }
      if(this.youhuashiId != 0){
        params.optid = this.youhuashiId
      }
      if (this.product_name != 0) {
        params.product_name = this.product_name
      }
      getAccountSummary(params).then((res) => {
        if(res.errcode == 0){
          this.totalList = res.data
        }
      });
    },
    getUserData() {
      // 获取账户信息
      getBdAccountList({}).then((res) => {
        if(res.errcode == 0){
          let arr = []
          for(let i of res.data){
            if(i.pid == 0){
              arr.push(i)
            }
          }
          this.userData = arr
        }
      });
    },
    getOptimizerList(){
      // 获取优化师列表
      getOptimizerList({}).then((res) => {
        if(res.errcode == 0){
          this.youhuashi = res.data.filter(item => item.username != '龚祺')
          this.setYouhuashiId()
        }
      });
    },
    setYouhuashiId() {
      if (this.isoptimizer == 1) {
        let youhuashiId = this.$store.state.user.userInfo.admin_user_id
        let f = this.youhuashi.find(e => e.id == youhuashiId)
        if (f) {
          this.youhuashiId = youhuashiId
        } else {
          this.youhuashiId = 0
        }
      }
    },
    getProductList(){
      let params = {
        page: 1,
        pagesize: 99999,
      }
      getProductList(params).then((res) => {
        if(res.errcode == 0){
          this.productList = res.data.productList
        }
      }).catch(() => {
        this.loading = false
      });
    },
    formDateChange(e) {
      // 时间选择
      if(e.length == 0){return}
      this.form.start_date = e[0].format("YYYY-MM-DD")
      this.form.end_date = e[1].format("YYYY-MM-DD")
      this.getData()
    },
    getLastUpdateTime() {
      // 获取最后更新时间
      getLastUpdateTime({}).then((res) => {
        if(res.errcode == 0){
          this.lastUpdateTime = res.data[0].lasttime
        }
      }).catch(() => {
        
      });
    },
    onChange(pagination, filters, sorter) {
      console.log(pagination, filters, sorter, this.columns.length)
      this.pageSize = pagination.pageSize
      this.page = pagination.current
      let arr = ['profit']
      if(this.page == pagination.current && !arr.includes(sorter.columnKey)){
        this.getSorter(sorter)
        // this.getRiData()
      }
      this.page = pagination.current
      // this.setData()
    },
    setData() {
      this.$nextTick(() => {
        const dataSource = deepCopyArray(this.dataSource)
        let idx = dataSource.findIndex(e => e.userName == '汇总')
        dataSource.splice(idx, 1)
        console.log(idx, dataSource);
        dataSource.unshift(Object.assign({
          userName:'汇总',
          username:'龚祺',
          product_name:'汇总',
        }, this.totalData))
        this.dataSource = dataSource
      })
    },
    watchWindowWidth() {
      let width = window.innerWidth
      if(width<=1600){
        this.labelAlign = "left"
      }else{
        this.labelAlign = "right"
      }
    },
    getSorter(sorter){
      if(sorter.column){
        this.changeKey = sorter.column.dataIndex
        switch(sorter.order){
          case "ascend":
            this.changeOrder = 'ASC'
            break
          case "descend":
            this.changeOrder = 'DESC'
            break
        }
      }else{
        this.changeKey = ''
        this.changeOrder = ''
      }
    },
    disabledDate(current){
      return current && ( current < moment().endOf('day').add(-100, 'days') || current > moment().endOf('day').add('days')) ;
    },
    xlsxName(name){
      let xlsxName = ''
      if (this.youhuashiId != 0) {
        let yhs = this.youhuashi.find(e => e.id == this.youhuashiId)
        if (yhs) {
          name += '-' + yhs['username']
        }
      }
      switch(this.chartTimeSelect){
        case '1':case 1:
          xlsxName = name + '-' + moment().format("YYYY年MM月DD日")
        break;
        case '2':case 2:
          xlsxName = name + '-' + moment().add(-1, 'day').format("YYYY年MM月DD日")
        break;
        case '3':case 3:
          xlsxName = name + '-' + moment().add(-7, 'days').format("YYYY年MM月DD日") + '至' + moment().add(-1, 'days').format("YYYY年MM月DD日")
        break;
        case '4':case 4:
          xlsxName = name + '-' + moment().add(-30, 'days').format("YYYY年MM月DD日") + '至' +  moment().add(-1, 'days').format("YYYY年MM月DD日")
        break;
        case '5':case 5:
          xlsxName = name + '-' + moment().startOf('month').format("YYYY年MM月DD日") + '至' +  moment().format("YYYY年MM月DD日")
        break;
        case '6':case 6:
          xlsxName = name + '-' + moment().startOf('quarter').format("YYYY年MM月DD日") + '至' +  moment().format("YYYY年MM月DD日")
        break;
        case '7':case 7:
          xlsxName = name + '-' + moment(this.form.start_date).format("MM月DD日") + '至' + moment(this.form.end_date).format("MM月DD日")
        break;
      }
      return xlsxName
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
  },
  computed:{
    isoptimizer() {
      const userInfo = this.$store.state.user.userInfo
      return userInfo ? userInfo.isoptimizer : 1
    },
  },
  deactivated() {
    this.$EventBus.$off('onresize', this.watchWindowWidth)
  },
  beforeDestroy() {
    this.$EventBus.$off('onresize', this.watchWindowWidth)
  },
  components:{CustomTable,countTo}
}
</script>

<style lang="less" scoped>
.container{
  .card{
    margin-bottom: 20px;
  }
  .area{
    display: flex;
    align-items: center;
  }
  .fontGreen{
    margin-left: 10px;
    color: #41b883;
  }
  .fontRed{
    margin-left: 10px;
    color: #c96168;
  }
  .customTable{
    margin-top: 20px;
  }
}
.search{
  background-color: #ffffff;
  padding: 12px;
  border-radius: 8px;
  margin-top: 20px;
}

.card-container {
  overflow: hidden;
}
.card-container > .ant-tabs-card > .ant-tabs-content {
  height: 120px;
  margin-top: -16px;
}

.card-container > .ant-tabs-card > .ant-tabs-content > .ant-tabs-tabpane {
  background: #fff;
  padding: 16px;
}

.card-container > .ant-tabs-card > .ant-tabs-bar {
  border-color: #fff;
}

.card-container > .ant-tabs-card > .ant-tabs-bar .ant-tabs-tab {
  border-color: transparent;
  background: transparent;
}

.card-container > .ant-tabs-card > .ant-tabs-bar .ant-tabs-tab-active {
  border-color: #fff;
  background: #fff;
}

.totalContainer{
  background-color: #f0f2f5;
}
.total-col{
  margin-top: 20px;
  padding: 0;
  background-color: transparent;
}
.total-item{
  display: flex;
  flex-direction: column;
  padding: 10px 20px;
  background-color: #ffffff;
  border-radius: 8px;
  .title{
    // font-weight: 700;
    // font-size: 22px;
    // color: #545b66;
    color: rgba(0,0,0,.45);
    font-size: 14px;
    line-height: 22px;
    white-space: nowrap;
  }
  .p{
    color: #222222;
    font-size: 22px;
    margin-top: 20px;
  }
}
</style>
<style lang="less">
.zhanlue{
  .ant-table-row-level-0:first-child{
    font-weight: 700;
  }
}
</style>